/**
*
* TÃ¢che pÃ©riodique sans mÃ©moire d'activation
*  Copyright (c) 2009 Ecole Centrale de Nantes IRCCyN
* see <a href="{@docRoot}/Documentation/task.html"> for more information</a>
* 
* @author: Richard
* @version 3.2
*/

package storm.Tasks;

import java.util.Iterator;

import report.system;
import storm.Entity;
import storm.EvtContext;
import storm.Timer;
import storm.Processors.Processor;
import storm.Tasks.Task.Activation;
import log.TaskTrace;

/**
 * 
 * @author richard
 *
 */
public class PTask_WAM extends PTask{
	int compteurActivation=0;
	/**
	 * 
	 */
	public void controleDealine(){
		super.controleDealine();
		
	}
	/**
	 * 
	 */
	public void rearmTimer(){
		super.rearmTimer();
		Activation B = new Activation(this.Kernel.getTime()+1);
		this.ActivationFIFO.addLast(B);
		compteurActivation = compteurActivation+1;
		Timer timerD = new Timer("controleDealine", (int)this.deadline,this);
		if (this.isEverRunning())Kernel.addTimer(timerD);
	//	System.out.println(this.Kernel.getTime() + "   "  + compteurActivation);
	}
	/**
	 * 
	 */
	public void onActivate(EvtContext c) {
		super.onActivate(c);
		compteurActivation = compteurActivation+1;
	}
	/**
	 * 
	 */
	public void finished(){
		

		if (this.compteurActivation > 1 ) {
			this.raiseUnBlock(this);
			
		}
		
		//System.out.println(this.Kernel.getTime() + "   "  + compteurActivation  );
		compteurActivation = compteurActivation-1;
		if (this.compteurActivation < 0) this.compteurActivation =0;
		super.finished();
	}
	/**
	 * 
	 */
	public void inRunning(){
		/**
		 * begin
		 */
		if(  (this.ET ==1 ) && (this.getRET()>=0 )) {
			Iterator I= this.ActivationFIFO.iterator();
			while (I.hasNext()) {
				Activation A = (Activation) I.next();
				if (A.getDeb_exec()< 0 ){
					A.setDeb_exec(this.Kernel.getTime());
					break;
				}
			}
		}
		/** 
		 * end
		 */
		if(  (this.ET > 0 ) && (this.getRET()== 0)) {
			Iterator I= this.ActivationFIFO.iterator();
			while (I.hasNext()) {
				Activation A = (Activation) I.next();
				if (A.getEnd_exec()< 0 ){
					A.setEnd_exec(this.Kernel.getTime());
					break;
				}
				}
		}
		super.inRunning();
	}
	/**
	 * 
	 */
	public void onTick(){
		super.onTick();
		if (this.isDeadline) {
			Iterator I= this.ActivationFIFO.iterator();
			while (I.hasNext()) {
				Activation A = (Activation) I.next();
				if (A.getDeadline()<0) {
					A.setDeadline(this.Kernel.getTime()+1);
					if (A.getEnd_exec() < 0 )  this.Kernel.getLogs().addTrace(new TaskTrace(this.Kernel.getTime(),this, TaskTrace.Type.FAILED,A.getDate()));
					break;
				}
			}
			this.isDeadline = false;
		}
	}
	/*public void onBlock(Entity A, EvtContext c) {
		super.onBlock(A,c);
		if (this == A) {
			if (this.compteurActivation > 0 ) {
				//this.raiseUnBlock(this);
			//	this.removeBlock(A);
			}
		}
				
	}*/
}

